package com.zhaojun.cloud.support.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhaojun.cloud.common.mapper.service.IUserAccessService;
import com.zhaojun.cloud.common.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * wwj
 * 2018/11/15  13:58
 */
@Component
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private IUserAccessService userAccessService;

    /**
     * 细化权限
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();

        Long userId = user.getId();
        //查询权限关联
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        permsSet.add("sys:user:info");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 登录
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        //查询用户信息
        User user = userAccessService.getOne(new QueryWrapper<User>().eq("username", usernamePasswordToken.getUsername()));
        //账号不存在
        if (user == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }

        //账号锁定
        if (user.getStatus() == "0") {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        //把user信息直接放到了信息当中去了
        return new SimpleAuthenticationInfo(user, user.getPassword(), new Md5Hash(user.getUsername()), getName());
    }

    /**
     * 设置认证加密方式
     */
    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher md5CredentialsMatcher = new HashedCredentialsMatcher();
        md5CredentialsMatcher.setHashAlgorithmName(ShiroKit.hashAlgorithmName);
        md5CredentialsMatcher.setHashIterations(ShiroKit.hashIterations);
        super.setCredentialsMatcher(md5CredentialsMatcher);
    }
}
